extends Area2D

class_name EnemyBase

var fire_timer: Timer
var visible_on_screen_notifier: VisibleOnScreenNotifier2D
var got_hit_audio: AudioStreamPlayer
var hit_processed = false
var hp: int = 1

var speed
var flying_direction

signal hit(target: Node, enemy: Node)

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	add_to_group("enemies")
	area_entered.connect(_on_area_entered)
	fire_timer = Timer.new()
	fire_timer.autostart = false
	fire_timer.one_shot = false
	fire_timer.timeout.connect(_on_fire_timer_timeout)
	add_child(fire_timer)
	
	visible_on_screen_notifier = VisibleOnScreenNotifier2D.new()
	visible_on_screen_notifier.screen_exited.connect(_on_screen_exited)
	add_child(visible_on_screen_notifier)
	
	got_hit_audio = AudioStreamPlayer.new()
	got_hit_audio.stream = preload("res://assets/sound/enemy_hit.mp3")
	got_hit_audio.autoplay = false
	add_child(got_hit_audio)
	
	speed = randf() * 500 + 100

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	position += flying_direction * speed * delta

func _on_fire_timer_timeout() -> void:
	fire()

func _on_area_entered(area: Area2D) -> void:
	hp -= 1
	if hp == 0:
		hit.emit(area, self)
		if area and area.is_visible_in_tree() and not hit_processed:
			hit_processed = true
			speed = 0
			await animate_explosion()
			queue_free()
	else:
		got_hit_audio.play()
		flash()
	if is_instance_valid(area) and area.is_in_group("bullets"):
		area.queue_free()

func _on_screen_exited() -> void:
	queue_free()

func flash():
	"""
	此函数用来提供敌机被击中时的闪烁效果
	"""
	var tween = create_tween()
	tween.tween_property($AnimatedSprite2D, "modulate", Color.from_rgba8(64, 64, 64), 0.08) # 深色，表示被击中
	tween.tween_property($AnimatedSprite2D, "modulate", Color.from_rgba8(255, 255, 255), 0.0)  # 恢复正常

func fire() -> void:
	"""
	此函数需要在子类中重载
	"""
	pass
	
func animate_explosion() -> void:
	"""
	此函数需要在子类中重载
	"""
	pass
